#! /bin/sh

TIME_ZONE=${TIME_ZONE:-"Asia/Shanghai"}
echo "$TIME_ZONE" > /etc/timezone
ln -sf /usr/share/zoneinfo/$TIME_ZONE /etc/localtime

DB_NAME=${DB_NAME:-""}
DB_USER=${DB_USER:-""}
DB_PWD=${DB_PWD:-""}
DB_ROOT_PWD=${DB_ROOT_PWD:-""}
DB_HOST=${DB_HOST:-"%"}

supervisor_start() {
    sed -i "s/;nodaemon=false/nodaemon=true/" /etc/supervisord.conf
    if [ ! -d "/etc/supervisor.d/" ]; then
        mkdir /etc/supervisor.d/
    fi

    supervisor_log_dir="/var/log/supervisor/"
    if [ ! -d $supervisor_log_dir ]; then
        mkdir $supervisor_log_dir
    fi

    mariadb_conf=/etc/supervisor.d/mariadb.ini
    if [ ! -e $mariadb_conf ]; then
        cat > /etc/supervisor.d/mariadb.ini << EOF
[program:mariadb]
directory=/
command=/usr/bin/mysqld_safe
user=root
autostart=true
autorestart=true
stdout_logfile=/var/log/supervisor/%(program_name)s.log
stderr_logfile=/var/log/supervisor/%(program_name)s.log
EOF
    fi

    /usr/bin/supervisord -c /etc/supervisord.conf
}


db_conf=/etc/mysql/my.cnf
db_data_dir="/var/lib/mysql/"
if [ `ls -A $db_data_dir | wc -w` -le 0 ]; then
    mysql_install_db --user=mysql --datadir=$db_data_dir --rpm

    tmp_sql=/tmp.sql
    cat << EOF > $tmp_sql
SET @@SESSION.SQL_LOG_BIN=0;
DROP DATABASE IF EXISTS test;
USE \`mysql\`;
DELETE FROM \`user\` WHERE User<>'root';
FLUSH PRIVILEGES;
EOF

    if [ -n $DB_NAME ]; then
        echo "CREATE DATABASE IF NOT EXISTS \`$DB_NAME\` CHARACTER SET utf8 COLLATE utf8_general_ci;" >> $tmp_sql
    	echo "FLUSH PRIVILEGES;" >> $tmp_sql
    fi

    if [[ -n $DB_USER && $DB_USER != 'root' ]]; then
        echo "CREATE USER '$DB_USER'@'$DB_HOST' IDENTIFIED BY '$DB_PWD';" >> $tmp_sql
        if [ -n $DB_NAME ]; then
            echo "GRANT ALL PRIVILEGES ON \`$DB_NAME\`.* TO '$DB_USER'@'$DB_HOST' WITH GRANT OPTION;" >> $tmp_sql
        fi
    	echo "FLUSH PRIVILEGES;" >> $tmp_sql
    fi

    if [ -n $DB_ROOT_PWD ]; then
        echo "UPDATE \`user\` SET Password=PASSWORD('$DB_ROOT_PWD') WHERE User='root' AND Host='localhost';" >> $tmp_sql
        echo "DELETE FROM \`user\` WHERE Password='';" >> $tmp_sql
    fi
    echo "FLUSH PRIVILEGES;" >> $tmp_sql

    /usr/bin/mysqld --user=mysql --bootstrap --verbose=0 < $tmp_sql 
    #mysqld_safe --skip-networking --nowatch
    #/usr/bin/mysqladmin -uroot --password="$DB_ROOT_PWD" shutdown

    rm -f $tmp_sql

    if [ ! -d "/run/sock/" ]; then
	mkdir "/run/sock"
    fi
    sed -i "/^\[mysqld]$/a pid-file\t= ${db_data_dir}mysql.pid" $db_conf
    sed -i "s/\/run\/mysqld\/mysqld.sock/\/run\/sock\/mysqld.sock/g" $db_conf
    chwon -R mysql:mysql /run/sock/
fi

supervisor_start
